<template>
    <div>

        <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item style="background: #e1e1e1" >
               <span style="color: black">分销设置</span>
            </el-form-item>
            <el-form-item label="消费获取积分比例" label-width="200" style="display: inline-block">
                <el-input v-model="formData.returnexchange"  type="number" style="width: 352px"></el-input>
                <span style="color: #222222;display: inline-block" >例：用户消费100元，如设置的比例为50%，那么会获取50的积分奖励，如果设置比例为10%，那么会获取10积分的奖励；用户获取积分（四舍五入）始终为整数。</span>
            </el-form-item>

                <el-form-item label="积分价值设置" label-width="200" style="width:80%;display: inline-block;">
                    <el-input v-model="formData.exchangevalue" placeholder="输入积分" style="width: 352px"></el-input>
                    <span style="color: #222222">  积分  =  </span>
                    <el-input v-model="formData.moneyvalue" placeholder="输入数值" style="width: 352px"></el-input>
                    <span style="color: #222222">  元  </span>
                </el-form-item>

<!--22222-->

            <el-form-item style="background: #e1e1e1" >
                <span style="color: black">参与积分兑换商品</span>
            </el-form-item>
            <el-form-item label="添加使用商品" label-width="200" style="display: inline-block;width:80%;">
                <el-checkbox v-model="mchecked">全部商品</el-checkbox>
                <el-button type="primary" style="display: inline-block;margin-left: 20px" :disabled=mchecked  @click.native="selectgoods()"> 添加商品</el-button>
                <div v-if="mchecked" style="display: inline-block;margin-left: 20px">
                    <span style="color: #222222;display: inline-block" >已选择</span>
                    <span  style="color: #222222;display: inline-block" >全部</span>
                    <span style="color: #222222;display: inline-block" >商品</span>
                </div>
                <div v-else style="display: inline-block;margin-left: 20px">
                    <span style="color: #222222;display: inline-block" >已选择</span>
                    <span  v-if="formData.usetype===0" style="color: #222222;display: inline-block" >{{formData.usetarget==""?"":formData.usetarget.split(",").length}}</span>
                    <span style="color: #222222;display: inline-block" >个商品</span>
                </div>
            </el-form-item>

                <el-form-item label="添加使用分类:" label-width="200" prop="toplevelproportion" style="width:80%;display: inline-block;">
                    <template>

                        <el-select v-model="topvalue" placeholder="请选择" @change="topchange1()" clearable>
                            <el-option
                                v-for="(item,index) in category"
                                :key="index"
                                :label="item.topcategoryname"
                                :value="item.topcategoryid">
                            </el-option>
                        </el-select>

                        <el-select v-model="secvalue" placeholder="请选择" clearable
                                   @change="secondchange1()">
                            <el-option
                                v-for="(item,index) in busCommoditySecondaryCategoryList"
                                :key="index"
                                :label="item.secondarycategoryname"
                                :value="item.secondarycategoryid">
                            </el-option>
                        </el-select>

                        <el-select v-model="thrvalue" placeholder="请选择" clearable @change="thirdchange1()">
                            <el-option v-for="(item,index) in busCommodityThirdCategoryList"
                                       :key="index"
                                       :label="item.thirdcategoryname"
                                       :value="item.thirdcategoryid">
                            </el-option>
                        </el-select>
                    </template>
                    <el-button type="primary" style="display: inline-block;margin-left: 20px" @click.native="AddCategories()"> 添加分类</el-button>
                </el-form-item>
                <el-form-item label="" label-width="200" prop="superiorproportion" style="margin-left:80px; width:30%;display: inline-block;border-bottom:1px solid #ebeef5;">
                    <div v-for="(item,index) in selectdata" :key="index">
                        <div style="display: inline-block">
                            <span style="color: #222222;display: inline-block" >{{item.name}}</span>
                        </div>
                        <el-button style="margin-left: 30px;" icon="el-icon-delete" @click.native="delbtn(index)"> </el-button>
                    </div>

                </el-form-item>

        </el-form>


        <span slot="footer" class="dialog-footer" style="margin-left: 29px;">
    <el-button type="primary" :loading="formSumbitLoding" @click="formSumbit" style="">提交</el-button>
  </span>

        <el-dialog
            title="选择商品"
            :visible.sync="goodsVisible"
            :close-on-click-modal="false"
            width="1000px"
            top="5vh"
            v-dialogDrag>
            <div>
                <getGoods @on-select="selectids" ></getGoods>
            </div>
        </el-dialog>

    </div>
</template>

<script>

    import {getBusCommodityExchange,updateBusCommodityExchange,getCategory} from "../../api/intergral/intergral";
    import getGoods from "../../components/goods/getGoods.vue";
    const formJson = {
        exchangeid:"",
        returnexchange:"",
        exchangevalue:"",
        moneyvalue:"",
        usetype:"",
        usetarget:""
    };
    export default {
        components: {
            getGoods
        },
        name: "distribution",
        data(){
            let validateNromalPercentAge = (rule, value, callback) => {
                if (!/^(?:0|[1-9][0-9]?|100)$/.test(value) ||
                    value == null ||
                    value == ""
                ) {
                    callback(new Error("请输入100以内的正整数"));
                } else {
                    callback();
                }
            };
            return {
                options:[],//分类选择
                selectdata:[], //分类data
                commodityids:[], //选择商品ids
                topvalue:"",
                secvalue:"",
                thrvalue:"",

                categoryobj: {},//分类列表
                SecondaryCategoryobj: {}, //二级
                ThirdCategoryobj: {},//三级

                category: [],//分类列表
                busCommoditySecondaryCategoryList: [], //二级
                busCommodityThirdCategoryList: [],//三级

                formSumbitLoding: false,//表单提交加载
                goodsVisible: false,
                mchecked: false, //
                formData:formJson,
                rules: {//表单校验

                    returnexchange: {
                        required: true,
                      //  message: "请输入百分比",
                        validator: validateNromalPercentAge,
                        trigger: "blur"
                    },
                    exchangevalue: {
                        required: true,
                        message: "请输入积分",
                        trigger: "blur"
                    },
                    moneyvalue: {
                        required: true,
                        message: "请输入金额",
                        trigger: "blur"
                    }
                }
            }
        },
        watch :{
            mchecked:function (val,oldval) {
                console.info("n:"+val+"--"+"o:"+oldval);
                if(val===true){
                    this.formData.usetarget="";
                    this.selectdata=[];
                    this.formData.usetype=0;
                }else{
                    this.formData.usetype=1;
                }
            }
        },
        methods :{
            //选择商品
            selectids(ids,v,name){
                this.goodsVisible=v;
                this.formData.usetarget = ids;
                this.formData.usetype=0;
                this.selectdata=[];

                console.info(name);
            },

            selectgoods(){
               // alert("添加商品");
                this.goodsVisible=true;
            },

            //添加分类
            AddCategories(){
               // alert("添加分类");
                this.formData.usetype=1;
                let cdata = {
                    id:"",
                    name:""
                }
                let flag=false;
                if(this.topvalue!==undefined&&this.topvalue!=""){
                    console.info(this.topvalue);

                    if(this.topvalue!=""){
                        cdata.id=this.topvalue;
                        cdata.name=this.categoryobj.topcategoryname
                    }
                    if(this.secvalue!=""){
                        cdata.id=this.topvalue+","+this.secvalue;
                        cdata.name=this.categoryobj.topcategoryname+","+this.SecondaryCategoryobj.secondarycategoryname;
                    }
                    if(this.thrvalue!=""){
                        cdata.id=this.topvalue+","+this.secvalue+","+this.thrvalue
                        cdata.name=this.categoryobj.topcategoryname+","+this.SecondaryCategoryobj.secondarycategoryname+","+this.ThirdCategoryobj.thirdcategoryname
                    }

                for (let i;i<this.selectdata.length;i++){
                    if(this.selectdata[i].id === cdata.id){
                        flag=true;
                    }
                }

               if(!flag){
                   this.selectdata.push(cdata);
                   cdata={};
                   this.topvalue="";
                   this.secvalue="";
                   this.thrvalue="";

                   this.categoryobj={};
                   this.SecondaryCategoryobj={};
                   this.ThirdCategoryobj={};

               }else{
                   alert("数据已存在");
               }
                }else { alert("请选择分类");}
            },
            //删除分类
            delbtn(index){
                this.selectdata.splice(index, 1);
            },

            //展示
            /*获取列表事件*/
            getList() {
                this.loading = true;
                getBusCommodityExchange().then(response => {
                    if (response.code != 0) {
                        this.$message.error(response.message);
                        return false;
                    }

                    let datalist = response.data || [];
                    console.info(datalist);
                    if(datalist!=null) {
                        this.formData=datalist;
                        if(datalist.usetype===0){
                          //  this.commodityids=datalist.usetarget.split(",");
                            if(datalist.usetarget===""&&datalist.usetype.toString()==="0"){
                             this.mchecked=true;
                            }
                        }if(datalist.usetype===1){
                            this.selectdata=JSON.parse(datalist.usetarget);
                        }


                    }else{
                        this.$message.error(response.message);
                        return false;
                    }
                    setTimeout(() => {
                        this.loading = false;
                    }, 0.3 * 1000);
                }).catch(() => {
                    this.loading = false;
                    this.formData = formJson;
                })
            },

            //add一级
            topchange1() {
                for (var i = 0; i < this.category.length; i++) {
                    if (this.category[i].topcategoryid == this.topvalue) {
                        this.busCommoditySecondaryCategoryList = this.category[i].busCommoditySecondaryCategoryList;
                        this.categoryobj=this.category[i];

                        break;
                    }
                }
            },
            //add二级
            secondchange1() {
                for (var i = 0; i < this.busCommoditySecondaryCategoryList.length; i++) {
                    if (this.busCommoditySecondaryCategoryList[i].secondarycategoryid == this.secvalue) {
                        this.busCommodityThirdCategoryList = this.busCommoditySecondaryCategoryList[i].busCommodityThirdCategoryList;
                        this.SecondaryCategoryobj=this.busCommoditySecondaryCategoryList[i];

                        break;
                    }
                }
            },
            thirdchange1()
            {

                for (var i = 0; i < this.busCommodityThirdCategoryList.length; i++) {
                    if (this.busCommodityThirdCategoryList[i].thirdcategoryid == this.thrvalue) {
                        this.ThirdCategoryobj=this.busCommodityThirdCategoryList[i];

                        break;
                    }
                }
            },
            //获得分类
            getAllCategory() {
                this.loading = true;
                getCategory().then(response => {
                        if (response.code) {
                            this.$message.error(response.message);
                        }
                        let data = response.data || [];
                        this.category = data;
                        setTimeout(() => {
                            this.loading = false;
                        }, 0.3 * 1000);
                    })
                    .catch(() => {
                        this.loading = false;
                        this.list = [];
                        this.totalNumber = 0;
                    });
            },

            formSumbit() {
                //表单校验通过
                this.$refs["ruleForm"].validate(valid => {
                    if (valid) {
                        if(this.formData.usetype===1){
                            this.formData.usetarget=JSON.stringify(this.selectdata);
                        }
                        if(this.formData.usetype==1&&(this.formData.usetarget==""||this.formData.usetarget==undefined)){
                            this.$message.error("请选择目标分类");
                            return
                        }
                        this.formSumbitLoding = true;
                        console.info(this.formData);

                        var params = new URLSearchParams(this.formData);
                        updateBusCommodityExchange(params).then(response => {
                            this.formLoading = false;
                            if (response.code != 0) {
                                this.$message.error(response.message);
                                this.formSumbitLoding = false;
                                return false;
                            }
                            this.$message.success("操作成功");
                            this.formSumbitLoding = false;
                            // 清空表单
                            this.$refs["ruleForm"].resetFields();
                            //重新加载表格
                            this.getList();
                        });
                    }
                });
            }
        },
        created() {
            this.getAllCategory();
            this.getList();
        }

    }
</script>

<style scoped>

</style>


